/* eslint-disable no-console */
const express = require("express");
const jwt = require("jsonwebtoken");
const bcryptjs = require("bcryptjs");
const dbContext = require("./db");
const config = require("./config");
const adminRouter = require("./adminRouter");
const articleCategoryRouter = require("./articleCategoryRouter");
const productCategoryRouter = require("./productCategoryRouter");
const aboutusRouter = require("./aboutusRouter");
const recruitmentRouter = require("./recruitmentRouter");
const contactRouter = require("./contactRouter");
const uploadRouter = require("./uploadRouter");
const articleRouter = require("./articleRouter");
const productRouter = require("./productRouter");

const app = new express();

//解决跨域问题
// app.use((request,response,next)=>{
//     response.setHeader("Access-Control-Allow-Origin", "*")
// 	response.setHeader("Access-Control-Allow-Methods", "*")
// 	response.setHeader("Access-Control-Allow-Headers", "*")
// 	response.setHeader("Access-Control-Expose-Headers", "*")
// 	next()
// })

app.use(express.static(__dirname + "/public"));

app.use(express.json());
// app.use(bodyParser.urlencoded({
//     extended:false
// }))

const auth = (req, res, next) => {
  let users = null;
  try {
    const raw = String(req.headers.authorization).split(" ").pop();
    users = jwt.verify(raw, config.TokenSecret);
  } catch (error) {
    return res.status(401).json({
      message: "授权未通过:[" + error + "]",
    });
  }
  if (users) {
    dbContext.auth(users.id, users.name, (err, data) => {
      if (!err && data) {
        req.user = data;
        next();
      } else {
        return res.status(401).json({
          message: "授权未通过",
        });
      }
    });
  }
};

app.use("/api/admin", auth, adminRouter);
app.use("/api/articleCategory", auth, articleCategoryRouter);
app.use("/api/productCategory", auth, productCategoryRouter);
app.use("/api/aboutus", auth, aboutusRouter);
app.use("/api/recruitment", auth, recruitmentRouter);
app.use("/api/contact", auth, contactRouter);
app.use("/api/upload", auth, uploadRouter);
app.use("/api/article", auth, articleRouter);
app.use("/api/product", auth, productRouter);

app.post("/login", function (req, res) {
  let { username, password } = req.body;
  dbContext.login(username, (err, data) => {
    if (!err) {
      if (!data) {
        return res.status(422).json({
          message: "用户不存在",
        });
      }
      let isValid = bcryptjs.compareSync(password, data.password);
      if (!isValid) {
        return res.status(200).json({
          message: "密码不正确",
        });
      }
      const token = jwt.sign(
        {
          id: data.id,
          name: data.name,
          lastlogintime: data.lastlogintime,
        },
        config.TokenSecret,
        { expiresIn: config.TokenExpires }
      );
      res.status(200).json({
        token,
      });
    }
  });
});

app.post("/register", auth, (req, res) => {
  let { name, account, password } = req.body;
  dbContext.register(name, account, bcryptjs.hashSync(password, 10), (err) => {
    if (err) throw err;
    res.status(200).json({
      message: "添加成功",
    });
  });
});

app.listen(3000, (err) => {
  if (!err)
    console.log(
      "Successful Connection! Please Start Your Operation! The Port 3000"
    );
});
